import 'dart:math';
import '../core/api_response.dart';
import '../core/exceptions.dart';

class MockApiService {
  static const Duration _defaultDelay = Duration(milliseconds: 500);
  static const double _errorProbability = 0.05; // 5% 的错误概率

  static Future<ApiResponse<T>> simulateApiCall<T>(
    Future<T> Function() computation, {
    Duration? delay,
    double? errorProbability,
  }) async {
    try {
      // 模拟网络延迟
      await Future.delayed(delay ?? _defaultDelay);
      
      // 随机模拟网络错误
      final shouldError = Random().nextDouble() < (errorProbability ?? _errorProbability);
      if (shouldError) {
        final errors = [
          const NetworkException('网络连接失败'),
          const ServerException('服务器内部错误', statusCode: 500),
          const ServerException('服务器繁忙', statusCode: 503),
        ];
        throw errors[Random().nextInt(errors.length)];
      }

      // 执行实际计算
      final result = await computation();
      
      return ApiResponse.success(
        data: result,
        message: '操作成功',
      );
    } on ApiException catch (e) {
      return ApiResponse.error(
        error: e.message,
        statusCode: e.statusCode ?? 500,
      );
    } catch (e) {
      return ApiResponse.error(
        error: '未知错误: ${e.toString()}',
        statusCode: 500,
      );
    }
  }

  static Future<ApiResponse<void>> simulateVoidApiCall(
    Future<void> Function() computation, {
    Duration? delay,
    double? errorProbability,
  }) async {
    try {
      await Future.delayed(delay ?? _defaultDelay);
      
      final shouldError = Random().nextDouble() < (errorProbability ?? _errorProbability);
      if (shouldError) {
        final errors = [
          const NetworkException('网络连接失败'),
          const ServerException('服务器内部错误', statusCode: 500),
          const ValidationException('数据验证失败'),
        ];
        throw errors[Random().nextInt(errors.length)];
      }

      await computation();
      
      return ApiResponse.success(
        message: '操作成功',
      );
    } on ApiException catch (e) {
      return ApiResponse.error(
        error: e.message,
        statusCode: e.statusCode ?? 500,
      );
    } catch (e) {
      return ApiResponse.error(
        error: '未知错误: ${e.toString()}',
        statusCode: 500,
      );
    }
  }

  static Future<ApiResponse<T>> simulateGetApiCall<T>(
    T data, {
    Duration? delay,
    double? errorProbability,
  }) async {
    return simulateApiCall<T>(
      () async => data,
      delay: delay,
      errorProbability: errorProbability,
    );
  }
}